package lol.clann.minecraft.springboot.plugin.core.config.configurate;

import com.google.auto.service.AutoService;
import lol.clann.minecraft.springboot.api.spi.sbp.ApplicationRunListener;
import lol.clann.minecraft.springboot.api.model.message.MessageBuilder;
import relocate.com.google.common.reflect.TypeToken;
import relocate.ninja.leaping.configurate.ConfigurationNode;
import relocate.ninja.leaping.configurate.objectmapping.ObjectMappingException;
import relocate.ninja.leaping.configurate.objectmapping.serialize.TypeSerializer;
import relocate.ninja.leaping.configurate.objectmapping.serialize.TypeSerializers;
import org.springframework.boot.SpringApplication;

/**
 *
 * @author pyz
 * @date 2019/6/23 12:40 PM
 */
@AutoService(ApplicationRunListener.class)
public class SerializerMessageBuilder implements TypeSerializer<MessageBuilder>, ApplicationRunListener {

    @Override
    public void starting(SpringApplication application) {
        TypeSerializers.getDefaultSerializers().registerPredicate(typeToken -> MessageBuilder.class == typeToken.getRawType(), this);
    }

    @Override
    public MessageBuilder deserialize(TypeToken<?> type, ConfigurationNode value) throws ObjectMappingException {
        String rawText = value.getString();
        return MessageBuilder.from(rawText);
    }

    @Override
    public void serialize(TypeToken<?> type, MessageBuilder obj, ConfigurationNode value) throws ObjectMappingException {
        value.setValue(obj.getRawText());
    }

}